package hwactor

import java.lang.System.currentTimeMillis

import akka.actor.{Actor, ActorSelection, ActorSystem, Props}
import com.typesafe.config.ConfigFactory

object NodeManagerInfo{
  val NMID = "nodemanage1"
}


class HeartBeatThread(myNodeManager:MyNodeManager) extends  Thread {

  override def run(): Unit ={
    while(true) {
      Thread.sleep(3000)
      myNodeManager.rmref ! new HearbeatMsg(NodeManagerInfo.NMID, System.currentTimeMillis())
    }
  }
}

class MyNodeManager extends  Actor{
  var rmref:ActorSelection= null
  def handleRegisteredNodeManager(hostname:String){
    println("MyNodeManager: 接收到MyResourceManager 注册成功的消息")
    new HeartBeatThread(this).start()
    //sender() ! new HearbeatMsg("NodeManager1", currentTimeMillis())
  }


  override def preStart(): Unit = {
    rmref = context.actorSelection("akka.tcp://MyResourceManagerActorSystem@localhost:19999/user/MyResourceManagerActor")
    rmref ! new RegisterMsg("NodeManager1" , 4, 2000)
  }

  override def receive: Receive = {
    case RegisteredNodeManager(hostname:String) =>{
      handleRegisteredNodeManager(hostname)
    }
  }
}

object MyNodeManager {
  def main(args: Array[String]): Unit = {
    val str=
      """
        |akka.actor.provider = "akka.remote.RemoteActorRefProvider"
        |akka.remote.netty.tcp.hostname = localhost
      """.stripMargin

    val config = ConfigFactory.parseString(str)
    val actorSystem = ActorSystem("MyNodeManagerActorSystem", config)
    actorSystem.actorOf(Props(new MyNodeManager()), "MyNodeManagerActor")
  }
}
